import axios, { AxiosRequestConfig, InternalAxiosRequestConfig } from 'axios'
import { message } from 'ant-design-vue'
import { useAuthStore } from '@/stores/auth'
import { handleMockRequest, isMockEnabled } from './mock'



// 创建 axios 实例
const apiClient = axios.create({
  baseURL: '/api',
  timeout: 30000,
  withCredentials: false,
  headers: {
    'Content-Type': 'application/json'
  }
})

// 请求拦截器 - 添加认证头和Mock处理
apiClient.interceptors.request.use(
  async (config: InternalAxiosRequestConfig) => {
    // 调试信息：记录请求URL
    console.log('[API] 发送请求:', {
      method: config.method?.toUpperCase(),
      url: config.url,
      fullURL: (config.baseURL || '') + (config.url || ''),
      params: config.params,
      data: config.data
    })

    // 如果启用了 Mock 模式，直接返回Mock响应
    if (isMockEnabled()) {
      const mockResponse = await handleMockRequest(config)
      // 抛出一个特殊错误，在响应拦截器中处理
      throw { __isMockResponse: true, response: mockResponse }
    }

    // 添加认证头
    const authStore = useAuthStore()
    const authHeaders = authStore.getAuthHeaders()
    
    Object.assign(config.headers, authHeaders)
    
    return config
  },
  (error) => {
    return Promise.reject(error)
  }
)

// 响应拦截器 - 处理认证失效和Mock响应
apiClient.interceptors.response.use(
  (response) => {
    // 调试信息：记录响应
    console.log('[API] 响应数据:', {
      url: response.config.url,
      status: response.status,
      data: response.data
    })

    // 检查业务错误码
    const data = response.data
    if (data && typeof data === 'object' && 'code' in data) {
      // 401认证失败特殊处理
      if (data.code === 401) {
        const authStore = useAuthStore()
        authStore.logout()
        window.location.href = '/login'
        message.error('认证失效，请重新登录')
        return Promise.reject(new Error('认证失效'))
      }
    }
    return response
  },
  (error) => {
    // 处理Mock响应
    if (error.__isMockResponse) {
      return Promise.resolve(error.response)
    }

    // 检查是否跳过错误消息显示
    const skipErrorMessage = error.config?.__skipErrorMessage

    if (error.response?.status === 401) {
      // Token过期，跳转到登录页
      const authStore = useAuthStore()
      authStore.logout()
      window.location.href = '/login'
      if (!skipErrorMessage) {
        message.error('认证失效，请重新登录')
      }
    } else {
      console.error('API Error:', error.response?.data || error.message)
      if (!skipErrorMessage) {
        message.error(error.response?.data?.msg || error.response?.data?.message || '请求失败')
      }
    }
    return Promise.reject(error)
  }
)

// 导出统一的请求客户端
export default apiClient

// 兼容旧的 request 函数
export async function request(url: string, options: RequestInit = {}) {
  try {
    const config: AxiosRequestConfig = {
      url,
      method: (options.method || 'GET') as any,
      data: options.body ? JSON.parse(options.body as string) : undefined,
      headers: options.headers as any
    }

    const response = await apiClient.request(config)
    
    return {
      ok: true,
      json: async () => response.data
    } as Response
  } catch (error: any) {
    throw error
  }
} 